package com.ruoyi.web.controller.home;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/home")
public class HomeController extends BaseController {
    @Autowired
    private IConsumeService consumeService;

    @Autowired
    private IFlowerClassService flowerClassService;

    @Autowired
    private IFlowerService flowerService;

    @Autowired
    private AddressService addressService;

    @PostMapping("/addaddress")
    public int addAddress(@RequestBody Address address,HttpSession session) {
        Consume consume = (Consume) session.getAttribute("user");
        address.setUserId(consume.getId());
        return addressService.insertAddress(address);
    }

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private IMasterOrderService masterOrderService;

    @PostMapping("/addorder/{id}")
    public int addorder(@PathVariable Long id,HttpSession session) {
        Map<Long, Flower> cart = (Map<Long, Flower>) session.getAttribute("cart");

        if(cart!=null) {

//
            //取出订单总价
            Float total = (Float) session.getAttribute("total");
            String orderNumber = getOrderId();//生成不会重复的订单号
            Consume user  = (Consume) session.getAttribute("user");
            MasterOrder order = new MasterOrder();
            order.setAddressId(id);
            order.setOrderNo(orderNumber);
            order.setUserId(user.getId());
            order.setState(1L);
            order.setUserName(user.getConsumeAccount());
            order.setTotalAmount(total);
            //调用添加订单的方法
            int count = masterOrderService.insertMasterOrder(order);


            //添加订单详情，一个订单对应多个订单详情
            //多少个订单详情取决于购物车里面有多少商品
            //订单主键id  商品主键id 购买商品数量   商品小计
            //创建订单详情的数据访问层对象

            //获取刚才插入的订单主键id
            Long orderId = masterOrderService.getMaxOrderId();


            //得到商品主键id 购买商品数量   商品小计
            Set<Long> set = cart.keySet();
            for (Long key : set) {
                //要得到数量和小计，那么就要得到商品对象
                Flower product = 	cart.get(key);
                long num = product.getBuyNum();//购买数量
                double cost = product.getAmount();//小计
                OrderItem orderItem = new OrderItem();
                orderItem.setMasterOrderId(orderId);
                orderItem.setName(product.getFlowerName());
                orderItem.setImg(product.getImg());
                orderItem.setNumber(num);
                orderItem.setPrice(product.getPrice());
                orderItemService.insertOrderItem(orderItem);
            }
            //清空购物车
            session.removeAttribute("cart");
            session.removeAttribute("total");
           session.removeAttribute("count");

        }
        return 1;
    }

    private String getOrderId() {
        String str= UUID.randomUUID().toString().replace("-", "").toUpperCase();

        return str;
    }


    @DeleteMapping("/delete/{id}")
    public int deleteAddress(@PathVariable Long id) {
        return addressService.deleteAddressById(id);
    }

    @GetMapping("/getByUserId")
    public List<Address> getAddressesByUserId(HttpSession session) {
        Consume consume = (Consume) session.getAttribute("user");
        return addressService.getAddressesByUserId(consume.getId());
    }

    @GetMapping("/list")
    public List<FlowerClass> list() {
        return flowerClassService.selectAllFlowerClasses();
    }

    @PostMapping("/flowerlist")
    public List<Flower> flowerList() {
        return flowerService.selectFlowerList(null);
    }

    @GetMapping("/flowers")
    @ResponseBody
    public PageInfo<Flower> getFlowerList(@RequestParam(defaultValue = "1") int pageNum,
                                          @RequestParam(defaultValue = "10") int pageSize) {
        return flowerService.getFlowerList(pageNum, pageSize);
    }

    @GetMapping("/product/{id}")
    public Flower product(@PathVariable Long id) {
        return flowerService.selectFlowerById(id);
    }

    @PostMapping("/messagesadd")
    public boolean messagesadd(@RequestBody Message message, HttpSession session) {
        Consume consume = (Consume) session.getAttribute("user");
        message.setUserId(consume.getId());
        if(messageService.insertMessage(message) >0){
            return  true;
        }else{
            return  false;
        }
    }

    @PostMapping("/update/{id}")
    public boolean add(@PathVariable Long id,HttpSession session) {
        Map<Long, Flower> cart = (Map<Long, Flower>) session.getAttribute("cart");
        Flower flower = cart.get(id);
        flower.setBuyNum(flower.getBuyNum()+1);
        flower.setAmount(flower.getPrice()* flower.getBuyNum());
        float total=0;
        Set<Long> set = cart.keySet();
        for (Long key : set) {
            Flower value = cart.get(key);
            total += value.getAmount();
        }
        session.setAttribute("total", total);
        session.setAttribute("cart", cart);
        return  true;
    }

    @PutMapping("/update/{id}")
    public boolean min(@PathVariable Long id,HttpSession session) {
        Map<Long, Flower> cart = (Map<Long, Flower>) session.getAttribute("cart");
        Flower flower = cart.get(id);
        flower.setBuyNum(flower.getBuyNum()-1);
        flower.setAmount(flower.getPrice()* flower.getBuyNum());
        float total=0;
        Set<Long> set = cart.keySet();
        for (Long key : set) {
            Flower value = cart.get(key);
            total += value.getAmount();
        }
        session.setAttribute("total", total);
        session.setAttribute("cart", cart);
        return  true;

    }

    @DeleteMapping("/update/{id}")
    public boolean remove(@PathVariable Long id,HttpSession session) {

        Map<Long, Flower> cart = (Map<Long, Flower>) session.getAttribute("cart");
        cart.remove(id);
        float total=0;
        Set<Long> set = cart.keySet();
        for (Long key : set) {
            Flower value = cart.get(key);
            total += value.getAmount();
        }
        session.setAttribute("total", total);
        session.setAttribute("cart", cart);
        return true;
    }



    @Autowired
    private IMessageService messageService;

    @GetMapping("/messages/{flowerId}")
    public List<Message> getMessages(@PathVariable Long flowerId) {
        return messageService.selectMessageByFlowerId(flowerId);
    }



    @PostMapping("/carts")
    @ResponseBody
    public Map carts(HttpSession session) {
        Map<Long, Flower> cart = (Map<Long, Flower>) session.getAttribute("cart");
        Float total = (Float) session.getAttribute("total");

        Set<Long> set = cart.keySet();
        int count = 0;
        for (Long key : set) {
            Flower value = cart.get(key);
            total += value.getAmount();
            count+=value.getBuyNum();
        }


        Map map = new HashMap();
        map.put("cart",cart);
        map.put("total",total);
        map.put("count",count);
        return map;
    }



    @GetMapping("/addcarts/{id}")
    public int addcarts(HttpServletRequest request,@PathVariable Long id){

        int buyNum = 1;//商品数量
        Flower goods = flowerService.selectFlowerById(id); //根据id查询商品信息
        int result = 0; //执行结果，库存不足-1，
        if (goods.getStock() < buyNum) {            //库存不足
            result = -1;
        } else {
            Map<Long, Flower> cart = (Map<Long, Flower>) request.getSession().getAttribute("cart");
            if (cart == null) {//是第一次把商品加入到购物车，之前购物车是不存在的
                cart = new HashMap<Long, Flower>();
            }
            Flower cartGoods = cart.get(id);
            if (cartGoods != null) {//如果不为空，就应用累加上次购买的数量
                if (cartGoods.getBuyNum() + buyNum < goods.getStock()) {
                    cartGoods.setBuyNum(buyNum + cartGoods.getBuyNum());
                    cartGoods.setAmount(cartGoods.getPrice() * cartGoods.getBuyNum());
                    cart.put(id, cartGoods);
                } else {
                    result = -1;
                }

            } else {
                goods.setBuyNum(buyNum);
                goods.setAmount(goods.getPrice() * buyNum);
                cart.put(id, goods);

            }

            float total = 0;
            Set<Long> set = cart.keySet();
            for (Long key : set) {
                Flower value = cart.get(key);
                total += value.getAmount();
            }
            request.getSession().setAttribute("total", total);
            request.getSession().setAttribute("cart", cart);
        }
        return result;
    }
    @RequestMapping("/total")
    public Float getTotal(HttpSession session){
        Map<Long, Flower> cart = (Map<Long, Flower>)session.getAttribute("cart");
        float total = 0;
        Set<Long> set = cart.keySet();
        for (Long key : set) {
            Flower value = cart.get(key);
            total += value.getAmount();
        }
        return  total;
    }

    // 注册接口
    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestBody Consume consume) {
        if (consumeService.insertConsume(consume)>0) {
            return "true";
        }
        return "false";
    }

    // 登录接口
    @GetMapping("/login")
    @ResponseBody
    public String login(@RequestParam String account, @RequestParam String password, HttpSession session) {
        Consume user = consumeService.selectConsumeByAccount(account);
        if (user != null && user.getConsumePassword().equals(password)) {
            session.setAttribute("user",user);
            return "true";
        }
        return "false";
    }
}
